<template>
  <div class="message">
    <div class="header">
      <van-row type="flex" align="center" justify="space-between">
        <van-col
          ><h4 v-if="unread_count">消息{{ "(" + unread_count + ")" }}</h4>
          <h4 v-else>消息</h4></van-col
        >
        <van-col
          ><van-icon
            name="volume"
            color="#fcd231"
            size="20"
            :dot="sys_msg_unread_count > 0 ? true : false"
            @click="$router.push('/notifications')"
        /></van-col>
      </van-row>
    </div>
    <div>
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <ChatUser v-for="user in list" :key="user.id" :user="user" />
      </van-list>
    </div>
  </div>
</template>

<script>
import { chatRecentAPI, unreadSysMsgCountAPI } from "@/api/userApi";
import ChatUser from "@/components/Chat/ChatUser";
import { mapState } from "vuex";
export default {
  components: {
    ChatUser,
  },
  data() {
    return {
      list: [],
      page: 1,
      loading: false,
      finished: false,
      sys_msg_unread_count: 0,
    };
  },
  computed: {
    ...mapState("chat", ["newMsg"]),
    unread_count() {
      let initV = 0;
      return this.list.reduce((previous, current) => {
        return previous + current.unread_message;
      }, initV);
    },
  },
  methods: {
    async onLoad() {
      const { data: res } = await chatRecentAPI(this.page);
      this.list = [...this.list, ...res.results];
      // 加载状态结束
      this.loading = false;
      this.page++;
      // 数据全部加载完成
      if (!res.next) {
        this.finished = true;
      }
    },
    async getSysMsgUnreadCount() {
      const { data: res } = await unreadSysMsgCountAPI();
      if (res.message == "OK") {
        this.sys_msg_unread_count = res.count;
      }
    },
    refresh() {
      this.list = [];
      this.page = 1;
      this.loading = false;
      this.finished = false;
    },
  },
  watch: {
    newMsg() {
      this.refresh();
    },
  },
};
</script>

<style lang="less" scoped>
.message {
  color: #191919;
}
.header {
  background: #f8f8f8;
  padding: 10px 10px;
  line-height: 22px;
}
.header h4 {
  margin: 0;
  font-weight: 400;
  font-size: 22px;
}
</style>